package com.ztewatch.wearcontacts.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.CursorLoader;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.RawContacts;

public class ConfigLoaderSelectionUtils {
	private static final String SORT_KEY_ORDER = Contacts.PINNED
			 + " COLLATE NOCASE DESC";
	public static void configGroupSelection(CursorLoader loader,
			long directoryId, long groupId) {
		StringBuilder selection = new StringBuilder();
		List<String> selectionArgs = new ArrayList<String>();
		String DATA_JOIN_MIMETYPES = "data JOIN mimetypes ON (data.mimetype_id = mimetypes._id)";
		selection.append(Contacts._ID + " IN " + "(SELECT "
				+ RawContacts.CONTACT_ID + " FROM  RAW_CONTACTS " + " WHERE "
				+ RawContacts.DELETED + "=0 AND RAW_CONTACTS._ID IN "
				+ "(SELECT DATA.RAW_CONTACT_ID" + " FROM "
				+ DATA_JOIN_MIMETYPES + " WHERE " + Data.MIMETYPE + "='"
				+ GroupMembership.CONTENT_ITEM_TYPE + "' AND "
				+ GroupMembership.GROUP_ROW_ID + "=" + "(SELECT GROUPS._ID"
				+ " FROM GROUPS " + " WHERE " + Groups._ID + "=?)))");
		selectionArgs.add(String.valueOf(groupId));
		loader.setSelection(selection.toString());
		loader.setSelectionArgs(selectionArgs.toArray(new String[0]));
		loader.setSortOrder(SORT_KEY_ORDER);
	}

	public static void configNotGroupedSelection(CursorLoader loader,
			long directoryId) {
		StringBuilder selection = new StringBuilder();
		List<String> selectionArgs = new ArrayList<String>();
		String DATA_JOIN_MIMETYPES = "data JOIN mimetypes ON (data.mimetype_id = mimetypes._id)";
		selection.append(Contacts._ID + " IN " + "(SELECT "
				+ RawContacts.CONTACT_ID + " FROM  RAW_CONTACTS " + " WHERE "
				+ RawContacts.DELETED + " = 0 AND RAW_CONTACTS._ID NOT IN "
				+ "(SELECT DATA.RAW_CONTACT_ID" + " FROM "
				+ DATA_JOIN_MIMETYPES + " WHERE " + Data.MIMETYPE + "='"
				+ GroupMembership.CONTENT_ITEM_TYPE + "'" + "))");
//		selection.append(" AND " + RawContacts.ACCOUNT_TYPE + "!=? AND "
//				+ RawContacts.ACCOUNT_TYPE + "!=?");
//		selectionArgs.add(SIMContactsContract.SIM_ACCOUNT_TYPE);
//		selectionArgs.add(SimContactsConstants.ACCOUNT_TYPE_SIM);

		loader.setSelection(selection.toString());
		loader.setSelectionArgs(selectionArgs.toArray(new String[0]));
	}
}
